/*
 * Matriz.java
 *
 * Created on 16/05/2014, 22:00:28 PM
 */
package matrizzaderenko;

import java.util.ArrayList;

import javax.swing.JOptionPane;

import javax.swing.table.DefaultTableModel;


/**
 *
 * @author Paul Yaguachi
 */
public class Matriz extends javax.swing.JFrame {

    ArrayList<String> t = new ArrayList<String>();
    int contador = 1;
    Integer arr[];
    Integer arr1[];
    Integer mat[][];
    String uno;

    /** Creates new form Matriz */
    public Matriz() {
        initComponents();
        generarMatriz.setEnabled(true);
        calcular.setEnabled(false);
        limpiar.setEnabled(false);
        tEarly.setEnabled(false);
      
        tLast.setEnabled(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        texto = new javax.swing.JLabel();
        texto2 = new javax.swing.JLabel();
        nNodos = new javax.swing.JTextField();
        generarMatriz = new javax.swing.JButton();
        matrizZaderenko = new javax.swing.JScrollPane();
        matriz = new javax.swing.JTable();
        tiempoEarly = new javax.swing.JScrollPane();
        tEarly = new javax.swing.JTable();
        tiempoLast = new javax.swing.JScrollPane();
        tLast = new javax.swing.JTable();
        calcular = new javax.swing.JButton();
        labelTiempoLast = new javax.swing.JLabel();
        limpiar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        texto.setFont(new java.awt.Font("Serif", 0, 24));
        texto.setText("Matriz de Zaderenko");
        jPanel1.add(texto, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 10, 210, 40));

        texto2.setText("Numero de nodos:");
        jPanel1.add(texto2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, -1, -1));

        nNodos.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                nNodosKeyTyped(evt);
            }
        });
        jPanel1.add(nNodos, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 60, 80, -1));

        generarMatriz.setText("Generar Matriz");
        generarMatriz.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                generarMatrizActionPerformed(evt);
            }
        });
        jPanel1.add(generarMatriz, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 60, -1, -1));

        matriz.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        matrizZaderenko.setViewportView(matriz);

        jPanel1.add(matrizZaderenko, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 130, 510, 240));

        tEarly.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Title 1"
            }
        ));
        tiempoEarly.setViewportView(tEarly);

        jPanel1.add(tiempoEarly, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 130, 110, 240));

        tLast.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tiempoLast.setViewportView(tLast);

        jPanel1.add(tiempoLast, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 380, 510, 50));

        calcular.setText("Calcular");
        calcular.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                calcularActionPerformed(evt);
            }
        });
        jPanel1.add(calcular, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 100, 90, -1));

        labelTiempoLast.setText("Tiempo Last");
        jPanel1.add(labelTiempoLast, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 404, -1, 10));

        limpiar.setText("Limpiar");
        limpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                limpiarActionPerformed(evt);
            }
        });
        jPanel1.add(limpiar, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 60, 100, -1));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 665, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 448, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void nNodosKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nNodosKeyTyped
// TODO add your handling code here:
    try {
        int k = (int) evt.getKeyChar();
        if (k >= 97 && k <= 122 || k >= 65 && k <= 90) {
            evt.consume();
            JOptionPane.showMessageDialog(null, "No puede ingresar Letras!!!", "Error Datos", JOptionPane.ERROR_MESSAGE);
        }
    } catch (Exception e) {
    }
}//GEN-LAST:event_nNodosKeyTyped

private void generarMatrizActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generarMatrizActionPerformed
if(nNodos.getText().equals("")){
     JOptionPane.showMessageDialog(null, "Ingrese un valor para generar la Matriz", "Aviso ", JOptionPane.INFORMATION_MESSAGE);
    
}else{
    
    DefaultTableModel llenadoMatriz = new DefaultTableModel(getFilasMatriz(), getColumnasMatriz());
    matriz.setModel(llenadoMatriz);
    
    DefaultTableModel llenadoTiempoEarly = new DefaultTableModel(getFilasTEarly(), getColumnasTEarly());
    tEarly.setModel(llenadoTiempoEarly);
    
    DefaultTableModel llenadoTiempoLast = new DefaultTableModel(getFilasTLast(), getColumnasTLast());
    tLast.setModel(llenadoTiempoLast);
    
    generarMatriz.setEnabled(false);
    calcular.setEnabled(true);
    matriz.setEnabled(true);
    matriz.requestFocus();
    
}
    
            
   
}//GEN-LAST:event_generarMatrizActionPerformed

private void calcularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_calcularActionPerformed
// TODO add your handling code here:
    limpiar.setEnabled(true);
    calcular.setEnabled(false);
    int x = Integer.parseInt(nNodos.getText());
    arr = new Integer[x];
    arr1 = new Integer[x];
    mat = new Integer[x][x];

    for (int i = 0; i < x; i++) {
        arr[i] = Integer.parseInt(tEarly.getValueAt(i, 0).toString());

    }
    for (int i = 1; i <= x; i++) {
        for (int j = 1; j <= x; j++) {
            if (matriz.getValueAt(i, j).toString().equals("")) {
                mat[i - 1][j - 1] = 111111;
            } else {
                mat[i - 1][j - 1] = Integer.parseInt(matriz.getValueAt(i, j).toString());
            }
        }
    }

    

//    -----------------------------calculo de tiempo early--0---------------------------
    int x1 = Integer.parseInt(nNodos.getText());
    int k = 0;
    int y = 0;
    int numeroMayor = 0;
    int res[];
    int e;
    for (int j = 1; j < x1; j++) {
        e=tamaño1(mat, j, x1);
        res=new int[e];
        k = 0;
        for (int i = 0; i < x1; i++) {
            if (mat[i][j] != 111111) {
                res[k] = arr[i] + mat[i][j];
                k++;
            }
            
        }
        numeroMayor = calcularMayor(res);
        y++;
        tEarly.setValueAt(numeroMayor, y, 0);
        for (int i = 0; i < x; i++) {
            arr[i] = Integer.parseInt(tEarly.getValueAt(i, 0).toString());
        }
    }
    
    tLast.setValueAt(Integer.parseInt(tEarly.getValueAt((x1-1), 0).toString()), 0, x-1);
    for (int i = 0; i < x; i++) {
        arr1[i] = Integer.parseInt(tLast.getValueAt(0, i).toString());
        System.out.println(arr1[i]);
    }
//    -----------------------------calculo de tiempo last--0---------------------------
    int x2 = Integer.parseInt(nNodos.getText());
    int k2 = 0;
    int y2 = x2-1;
    int numeroMenor = 0;
    int res2[];
    int e1;
    for (int i = (x2-2); i >=0; i--) {
     e1=tamaño(mat, i, x2);
           
     res2=new int[e1];
        k2 = 0;
 
        for (int j = x2-1; j >=0; j--) {
            
            if (mat[i][j] != 111111) {
                
                res2[k2] = arr1[j]-mat[i][j] ;
                
                System.out.println(""+arr1[j]+"-"+mat[i][j]+"="+(arr1[j]-mat[i][j]));
                
                k2++;
                
            }
            
        }
        
        
        numeroMenor = calcularMenor(res2);
        System.out.println("Otro");
        y2--;
        
        tLast.setValueAt(numeroMenor, 0, y2);
        for (int p = 0; p < x; p++) {
        arr1[p] = Integer.parseInt(tLast.getValueAt(0, p).toString());
        System.out.println(arr1[p]);
    }
 
    }
    matriz.setEnabled(false);

}//GEN-LAST:event_calcularActionPerformed

    private void limpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_limpiarActionPerformed
        // TODO add your handling code here:
        generarMatriz.setEnabled(true);
        limpiar.setEnabled(false);
        nNodos.setText("0");
        nNodos.requestFocus();
        DefaultTableModel llenadoMatriz = new DefaultTableModel(getFilasMatriz(), getColumnasMatriz());
        matriz.setModel(llenadoMatriz);
        DefaultTableModel llenadoTiempoEarly = new DefaultTableModel(getFilasTEarly(), getColumnasTEarly());
        tEarly.setModel(llenadoTiempoEarly);
        DefaultTableModel llenadoTiempoLast = new DefaultTableModel(getFilasTLast(), getColumnasTLast());
        tLast.setModel(llenadoTiempoLast);
        
    }//GEN-LAST:event_limpiarActionPerformed

    /**4
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Matriz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Matriz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Matriz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Matriz.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Matriz().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton calcular;
    private javax.swing.JButton generarMatriz;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel labelTiempoLast;
    private javax.swing.JButton limpiar;
    private javax.swing.JTable matriz;
    private javax.swing.JScrollPane matrizZaderenko;
    private javax.swing.JTextField nNodos;
    private javax.swing.JTable tEarly;
    private javax.swing.JTable tLast;
    private javax.swing.JLabel texto;
    private javax.swing.JLabel texto2;
    private javax.swing.JScrollPane tiempoEarly;
    private javax.swing.JScrollPane tiempoLast;
    // End of variables declaration//GEN-END:variables

    private Object[][] getFilasMatriz() {
        int x = Integer.parseInt(nNodos.getText());
        int k = 1;
        Object fila[][] = new Object[x + 1][x + 1];
        for (int i = 0; i < (x + 2); i++) {
            for (int j = 1; j < (x + 2); j++) {
                if (k <= x) {
                    fila[0][k] = j;
                    fila[k][0] = k;
                    k++;
                }
            }
        }

        for (int i = 1; i < x + 1; i++) {
            for (int j = 1; j < x + 1; j++) {
                fila[i][j] = "";
            }
        }

        return fila;
    }

    private String[] getColumnasMatriz() {
        int x = Integer.parseInt(nNodos.getText());
        String columna[] = new String[x + 1];
        for (int i = 0; i < (x + 1); i++) {
            columna[i] = "";
        }
        return columna;
    }

    private String[] getColumnasTEarly() {
        String columna[] = new String[1];
        for (int i = 0; i < 1; i++) {
            columna[i] = "Tiempo Early";
        }
        return columna;
    }

    private Object[][] getFilasTEarly() {
        int x = Integer.parseInt(nNodos.getText());

        Object fila[][] = new Object[x][1];
        for (int i = 0; i < (x); i++) {
            for (int j = 0; j < 1; j++) {
                fila[i][j] = 0;
            }

        }

        return fila;
    }

    private String[] getColumnasTLast() {
        int x = Integer.parseInt(nNodos.getText());
        String columna[] = new String[x];
        for (int i = 0; i < x; i++) {
            columna[i] = "" + (i + 1);
        }
        return columna;
    }

    private Object[][] getFilasTLast() {
        int x = Integer.parseInt(nNodos.getText());
        Object fila[][] = new Object[1][x];
        for (int i = 0; i < 1; i++) {
            for (int j = 0; j < x; j++) {
                fila[i][j] = 0;
            }

        }

        return fila;
    }

    private int calcularMayor(int[] a) {
        int resultado = a[0];
        for (int i = 0; i < a.length; i++) {
            if (a[i] > resultado) {
                resultado = a[i];
            }
        }
        return resultado;
    }
    
    private int calcularMenor(int[] a) {
        int resultado = a[0];
        
        for (int i = 0; i < a.length; i++) {
            if (a[i] < resultado) {
                resultado = a[i];
            }
        }
        return resultado;
    }
    private int tamaño(Integer[][] a,int n,int x) {
        int con=0;
        for (int j = 0; j < x; j++) {
            if (a[n][j]!=111111) {
                con++;
            }
        }
        return con;
    }
    
    private int tamaño1(Integer[][] a,int n,int x) {
        int con=0;
        for (int i = 0; i < x; i++) {
            if (a[i][n]!=111111) {
                con++;
            }
        }
        return con;
    }
}
